<?php

namespace App\Service\Cruise\Check;

use AlibabaCloud\SDK\OSS\OSS\SelectObjectRequest\body\selectRequest\options;
use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Jobs\Export\Export;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckCompanyModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseCheckRiskProblemModel;
use App\Models\Cruise\CruiseOrderInputModel;
use App\Models\Cruise\CruiseOrderInputTypeModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\BaseService;
use App\Service\Common\ExportService;
use App\Service\Cruise\Mission\CheckInputService;
use App\Service\Cruise\Mission\CommonInputService;
use App\Service\OpenShop\User\RmsUserService;
use App\Support\CustomForm\AttributeCruiseSupport;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cache;
use Kuafu\File\FileUtil;

class CruiseCheckReportService extends BaseService
{
    public function lists(
        int $startTime,
        int $endTime,
        int $dealUid,
        string $templateName,
        string $shop,
        int $sysTemplate,
        int $pageSize,
        int $pageNum,
        int $status,
        int $templateType,
        array $cruiseCheckCompanyIds = [],
        string $cruiseCheckRectifyStatus = '',
        string $inputType = '',
        string $taskName = '',
        array $templateIds = [],
        int $userId = 0,
        int $export = 0
    ) {

        $inputTypeTable = (new CruiseOrderInputTypeModel())->getTable();

        $paginator = CruiseCheckDetailModel::query()
                                           ->join($inputTypeTable . ' as inputTypes', 'inputTypes.orderId', '=', 'cruise_check_details.orderId')
                                           ->when($inputType,function ($query)use ($inputType,$status){
                                                if ($inputType == AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP && $status){
                                                    $query->whereHas('cruiseOrderRel',function ($_query)use ($status){
                                                        $_query->where('status',$status);
                                                    });
                                                } else {
                                                    $query->with('cruiseOrderRel');
                                                }
                                           })
                                           ->with('cruiseTaskRel')
                                           ->with('cruiseCheckRectify')
                                           ->with('templateRel')
                                           ->where('cruise_check_details.templateType', $templateType)
                                           ->where('inputTypes.inputType', $inputType)
                                           ->when($startTime, function ($query) use ($startTime) {
                                               $query->where('submitTime', '>=', $startTime);
                                           })
                                           ->when($endTime, function ($query) use ($endTime) {
                                               $query->where('submitTime', '<=', $endTime);
                                           })
                                           ->when($dealUid, function ($query) use ($dealUid) {
                                               $query->where('dealUid', $dealUid);
                                           })
                                           ->when($status, function ($query) use ($status,$inputType) {
                                               if ($inputType != AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP){
                                                   $query->where('reportResult', $status);
                                               }
                                           })
                                           ->when($templateName, function ($query) use ($templateName) {
                                               $query->whereRaw("taskId in (select `id` from `cruise_check_tasks` where `name` like '%$templateName%')");
                                           })
                                            ->when($templateIds, function ($query) use ($templateIds) {
                                                $query->whereIn('templateId',$templateIds);
                                            })
                                            ->when($taskName, function ($query) use ($taskName) {
                                                $query->where('taskName', 'like', "%$taskName%");
                                            })
                                           ->when(mb_strlen($cruiseCheckRectifyStatus), function ($query) use ($cruiseCheckRectifyStatus){
                                               switch ($cruiseCheckRectifyStatus) {
                                                   case CruiseCheckDetailModel::RECTIFY_STATUS_FINISH:
                                                       $query->where('failNum', '>', 0)->whereRaw("cruise_check_details.id not in (select `cruiseCheckDetailId` from `cruise_check_rectify` where `status` in (" . CruiseCheckRectifyModel::STATUS_WAIT_AUDIT . ", " . CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT . "))");
                                                       break;
                                                   case CruiseCheckDetailModel::RECTIFY_STATUS_WITH_NOT_NEED:
                                                       $query->whereRaw("cruise_check_details.id not in (select `cruiseCheckDetailId` from `cruise_check_rectify`)");
                                                       break;
                                                   case CruiseCheckDetailModel::RECTIFY_STATUS_RECTIFIED:
                                                       $query->whereRaw("cruise_check_details.id in (select `cruiseCheckDetailId` from `cruise_check_rectify` where `status` in (" . CruiseCheckRectifyModel::STATUS_WAIT_AUDIT . ", " . CruiseCheckRectifyModel::STATUS_WAIT_SUBMIT . "))");
                                                       break;
                                               }
                                           })
                                           ->when($sysTemplate, function ($query) use ($sysTemplate) {
                                               $query->where('sysTemplate', $sysTemplate);
                                           })
                                           ->when($shop, function ($query) use ($shop) {
                                               $shopIds   = ShopModel::getShopIdByGeneralSearch($shop);
                                               if ($shopIds) {
                                                   $orderId = CruiseOrderModel::query()
                                                                              ->whereIn('shopId', $shopIds)
                                                                              ->pluck('id');
                                                   $query->whereIn('cruise_check_details.orderId', $orderId);
                                               } else {
                                                   $query->where('cruise_check_details.id', 0);
                                               }
                                           })
                                            ->when($cruiseCheckCompanyIds, function ($query) use ($cruiseCheckCompanyIds) {

                                                $orderId = CruiseOrderModel::query()
                                                                           ->whereIn('cruiseCheckCompanyId', $cruiseCheckCompanyIds)
                                                                           ->pluck('id');
                                                $query->whereIn('cruise_check_details.orderId', $orderId);
                                            })
                                           ->whereIn('reportResult', [
                                               CruiseCheckDetailModel::REPORT_RESULT_QUALIFIED,
                                               CruiseCheckDetailModel::REPORT_RESULT_UNQUALIFIED,
                                               CruiseCheckDetailModel::REPORT_RESULT_CANCEL,
                                           ])
                                           ->where('submitTime', '>', 0)
                                           ->selectRaw('cruise_check_details.*, cruise_check_details.id as dId')
                                           ->orderByDesc('cruise_check_details.id');

        if ($export) {
            return $paginator;
        }

        $paginator = $paginator->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $shopIds = collect($paginator->items())->map(function ($item) {
            if (!$item->cruiseOrderRel) {
                return null;
            }

            return $item->cruiseOrderRel->shopId;
        })->filter()->values()->toArray();

        $shopInfos = collect((new RmsShopApi())->getShopByIds($shopIds,
                ['id', 'shopCode', 'name'])['data']['shopList'] ?? [])->keyBy('id');

        $shopCodes       = $shopInfos->pluck('shopCode');
        $merchantUserIds = OpenShopSignOrderModel::query()
                                                 ->whereIn('shopCode', $shopCodes)
                                                 ->orderByDesc('id')
                                                 ->select('shopCode', 'merchantUserId')
                                                 ->get()
                                                 ->keyBy('shopCode');

        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($merchantUserIds->pluck('merchantUserId')
                                                                                     ->toArray())['data'])->keyBy('id');
        return self::pageLists($paginator, function ($item) use ($shopInfos, $merchantUserIds, $userInfos, $inputType) {

            if (!$item->cruiseOrderRel) {
                return null;
            }

            $shopCode       = $shopInfos[$item->cruiseOrderRel->shopId ?? 0]['shopCode'] ?? '';
            $merchantUserId = $merchantUserIds[$shopCode]['merchantUserId'] ?? 0;

            // 工厂信息
            if ($item->cruiseOrderRel->cruiseCheckCompanyId) {
                $cruiseCheckCompany = CruiseCheckCompanyModel::getDataById($item->cruiseOrderRel->cruiseCheckCompanyId);
            } else {
                $cruiseCheckCompany = [];
            }
            $cruiseCheckRectifyText   = '无需整改';
            $cruiseCheckRectifyStatus = CruiseCheckDetailModel::RECTIFY_STATUS_WITH_NOT_NEED;
            foreach ($item->cruiseCheckRectify as $cruiseCheckRectify) {
                if ($cruiseCheckRectify->status != CruiseCheckRectifyModel::STATUS_FINISH) {
                    $cruiseCheckRectifyText   = '未完成';
                    $cruiseCheckRectifyStatus = CruiseCheckDetailModel::RECTIFY_STATUS_RECTIFIED;
                    break;
                }
                $cruiseCheckRectifyText   = '已完成';
                $cruiseCheckRectifyStatus = CruiseCheckDetailModel::RECTIFY_STATUS_FINISH;
            }

            $reportResult = $item->reportResult;
            $reportResultText = CruiseCheckDetailModel::REPORT_RESULT_MAPPING[$item->reportResult] ?? '';
            if ($inputType == AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP){
                $reportResult = $item->cruiseOrderRel->status;
                $reportResultText = CruiseOrderModel::CRUISE_STATUS_MAPPING[$reportResult] ?? '';
            }

            return [
                'id'                       => $item->id,
                'templateName'             => $item->cruiseOrderRel->getTaskName($item->taskId),
                'shopCode'                 => $shopCode,
                'shopName'                 => $shopInfos[$item->cruiseOrderRel->shopId ?? 0]['name'] ?? '',
                'merchantName'             => $userInfos[$merchantUserId]['username'] ?? '',
                'sysTemplate'              => $item->sysTemplate,
                'sysTemplateText'          => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$item->sysTemplate] ?? '',
                'dealName'                 => $item->dealName,
                'submitTime'               => $item->submitTime ? date('Y-m-d H:i:s', $item->submitTime) : '-',
                'actualScore'              => $item->totalScore != 0 ? (int)($item->actualScore / $item->totalScore * 100) : 0,
                'reportResult'             => $reportResult,
                'reportResultText'         => $reportResultText,
                'isSignature'              => $item->isSignature,
                'isSignatureText'          => $item->isSignature == 1 ? '是' : '否',
                'companyName'              => $cruiseCheckCompany['fsCompany']['name'] ?? '',
                'companyContact'           => $cruiseCheckCompany['companyManager']['phone'] ?? '',
                'companyId'                => $item->cruiseOrderRel->cruiseCheckCompanyId,
                'qualityScore'             => $item->qualityScore,
                'cruiseCheckRectifyText'   => $cruiseCheckRectifyText,
                'cruiseCheckRectifyStatus' => $cruiseCheckRectifyStatus,
                'cruiseTemplateName'       => (string)optional($item->templateRel)->name,
            ];
        });
    }

    public static function exportLists(array $params)
    {
        ini_set('memory_limit', '1024M');

        $data = $params['data'];

        $builder = (new self)->lists(
            $data['startDateTime'] ? strtotime($data['startDateTime'] ) : 0,
            $data['endDateTime'] ? strtotime($data['endDateTime']) : 0,
            $data['dealUid'],
            $data['templateName'],
            $data['shop'],
            $data['sysTemplate'],
            1000000,
            1,
            $data['status'],
            $data['templateType'],
            $data['cruiseCheckCompanyIds'],
            $data['cruiseCheckRectifyStatus'],
            $data['inputType'],
            $data['taskName'],
            $data['templateIds'] ?? [],
            $params['userId'],
            1
        );

        $inputType = $data['inputType'];

        $headers = [];
        if (in_array($inputType,[AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK,AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP])) {

            // 常规巡检项
            $headers = [
                '巡检日期', '门店编号', '门店名称', '战区', '省份', '城市', '巡检人', '巡检公司', '督导', '初审人', '初审驳回原因', '品控审核人', '品控驳回原因', '稽核项目', '稽核结果', '稽核照片', '问题描述/不适用原因', '整改类型', '门店整改建议', '现场整改照片', '最新整改时间', '整改状态', '整改审核结果', '整改次数', '是否手工有违约单', '是否系统自动触发违约单', 'id','模版总分','报告得分','实际得分(百分制)'
            ];
        } elseif ($inputType == AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_BIOLOGY) {

            // 生物巡检项
            $headers = [
                '巡检日期', '门店编号', '门店名称', '战区', '省份', '城市', '巡检人', '巡检公司', '督导', '初审人', '初审驳回原因', '品控审核人', '品控驳回原因', '稽核项目', '稽核结果', '稽核照片', '风险类型（一级）', '风险类型（二级）', '问题描述/不适用原因', '整改类型', '门店整改建议', '现场整改照片', '最新整改时间', '整改状态', '整改审核结果', '整改次数', '是否手工有违约单', '是否系统自动触发违约单', 'id'
            ];
        }

        $contents = [];

        $builder
            ->with('cruiseCheckRectify')
            ->with('cruiseCheckAgainst')
            ->with('processRel.examineLogRel')
            ->chunkById(200, function ($details) use (&$contents, $inputType) {

            $shopIds = $details->pluck('cruiseOrderRel.shopId')->toArray();
            $shops   = ShopModel::query()->whereIn('id', $shopIds)->get()->keyBy('id');

            $details->each(function (CruiseCheckDetailModel $checkDetailModel) use (&$contents, $shops, $inputType) {

                $cruiseOrder = $checkDetailModel->cruiseOrderRel;
                if (!$cruiseOrder) {
                    return;
                }

                $shopId           = (int)optional($checkDetailModel->cruiseOrderRel)->shopId;
                $addressPrefix    = $shops[$shopId]['addressPrefix'] ?? '';
                $addressPrefixArr = explode('-', $addressPrefix);
                $councilorId      = $shops[$shopId]['councilorId'] ?? 0;
                $provinceCode     = $shops[$shopId]['province'] ?? 0;
                $councilorName    = self::getUsername($councilorId);

                $inputObj = (new CommonInputService($checkDetailModel->orderId, $checkDetailModel->templateType, $checkDetailModel->sysTemplate, null));

                // 表单信息
                $inputs = $inputObj->getInputObjectFill();

                // cruise_order对应整改单
                $cruiseCheckRectifys = $checkDetailModel->cruiseCheckRectify->keyBy('field');

                $regionName = OpenShopRegionManageModel::getWarZoneInfoByProvinceCode($provinceCode, 'array')['regionName'] ?? '';

                foreach ($inputs['lists'] as $input) {
                    foreach ($input['projects'] as $project) {
                        switch ($project["inputType"]){
                            case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK:
                            case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP:
                            case AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_BIOLOGY:

                                $inputObj->setProject($project);
                                $cruiseCheckRectify = $cruiseCheckRectifys[$project['field']] ?? [];

                                // 手工违约函
                                $manualAgainst = $checkDetailModel->cruiseCheckAgainst
                                    ->where('templateType', CruiseCheckAgainstModel::TEMPLATE_TYPE_DEFAULT)
                                    ->first();

                                // 超期未整改违约函
                                $delayAgainst = $checkDetailModel->cruiseCheckAgainst
                                    ->where('templateType', CruiseCheckAgainstModel::TEMPLATE_TYPE_TIMEOUT)
                                    ->first();

                                // 初审人
                                $firstProcess = $checkDetailModel->processRel->where('step', CruiseOrderProcessModel::PROCESS_EXT_REVIEWED)->first();
                                $firstAuditUid = $firstProcess['createdByUid'] ?? 0;

                                // 初审驳回原因
                                $firstProcessReject = '';
                                if ($firstProcess && $firstProcess->status == CruiseOrderProcessModel::STATUS_OFF) {
                                    $firstProcessReject = $firstProcess->examineLogRel['content'] ?? '';
                                }

                                // 品控审核人
                                $kfAudit = $checkDetailModel->processRel->where('step', CruiseOrderProcessModel::PROCESS_REVIEWED)->first();
                                $kfAuditUid = $kfAudit['createdByUid'] ?? 0;

                                // 品控驳回原因
                                $kfProcessReject = '';
                                if ($kfAudit && $kfAudit->status == CruiseOrderProcessModel::STATUS_OFF) {
                                    $kfProcessReject = $kfAudit->examineLogRel['content'] ?? '';
                                }

                                // 整改次数
                                $replyCount = 0;
                                if ($cruiseCheckRectify) {
                                    $replyCount = $cruiseCheckRectify->replyRel->count();
                                }

                                if (in_array($inputType,[AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK,AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_SKIP])) {

                                    // 常规巡检项
                                    $contents[] = [
                                        date('Y-m-d H:i:s', $checkDetailModel->submitTime),
                                        $shops[$shopId]['shopCode'] ?? 0,
                                        $shops[$shopId]['name'] ?? '',
                                        $regionName,
                                        $addressPrefixArr[0] ?? '',
                                        $addressPrefixArr[1] ?? '',
                                        $checkDetailModel->dealName,
                                        $checkDetailModel->companyName ?: '-',
                                        $councilorName,
                                        self::getUsername($firstAuditUid),
                                        $firstProcessReject,
                                        self::getUsername($kfAuditUid),
                                        $kfProcessReject,
                                        $project['text'],
                                        $inputObj->checkResult(),
                                        $inputObj->checkImages(),
                                        $inputObj->desc(),
                                        $inputObj->rectifyStatusText(),
                                        $inputObj->rectifyDesc(),
                                        $inputObj->rectifyImages(),
                                        $inputObj->lastSubmitTime($cruiseCheckRectify),
                                        $inputObj->rectifyOrderStatus($cruiseCheckRectify),
                                        $inputObj->rectifyAuditResult($cruiseCheckRectify),
                                        $replyCount,
                                        $manualAgainst ? '是' : '否',
                                        $delayAgainst ? '是' : '否',
                                        $checkDetailModel->id,
                                        $checkDetailModel->totalScore,
                                        $checkDetailModel->actualScore,
                                        $checkDetailModel->totalScore != 0
                                            ? (int)($checkDetailModel->actualScore / $checkDetailModel->totalScore * 100)
                                            : 0
                                    ];
                                } elseif ($inputType == AttributeCruiseSupport::INPUT_TYPE_CRUISE_CHECK_BIOLOGY) {

                                    // 生物巡检项
                                    $value = $project['value'] ?? null;

                                    // 不合格，按问题描述+行
                                    if ($value == AttributeCruiseSupport::CRUISE_CHECK_FAIL) {

                                        // 问题描述
                                        $riskType2s = $project['customAttributes']['auditValue']['riskType2'] ?? [];

                                        foreach ($riskType2s as $riskType2) {

                                            $problemDescs = $inputObj->problemDesc($riskType2) ?: [''];
                                            foreach ($problemDescs as $problemDesc) {
                                                list($riskName1, $riskName2) = self::getRiskName12($riskType2);

                                                $contents[] = [
                                                    date('Y-m-d H:i:s', $checkDetailModel->submitTime),
                                                    $shops[$shopId]['shopCode'] ?? 0,
                                                    $shops[$shopId]['name'] ?? '',
                                                    $regionName,
                                                    $addressPrefixArr[0] ?? '',
                                                    $addressPrefixArr[1] ?? '',
                                                    $checkDetailModel->dealName,
                                                    $checkDetailModel->companyName ?: '-',
                                                    $councilorName,
                                                    self::getUsername($firstAuditUid),
                                                    $firstProcessReject,
                                                    self::getUsername($kfAuditUid),
                                                    $kfProcessReject,
                                                    $project['text'],
                                                    $inputObj->checkResult(),
                                                    $inputObj->checkImages(),
                                                    $riskName1,
                                                    $riskName2,
                                                    $problemDesc,
                                                    $inputObj->rectifyStatusText(),
                                                    $inputObj->rectifyDesc(),
                                                    $inputObj->rectifyImages(),
                                                    $inputObj->lastSubmitTime($cruiseCheckRectify),
                                                    $inputObj->rectifyOrderStatus($cruiseCheckRectify),
                                                    $inputObj->rectifyAuditResult($cruiseCheckRectify),
                                                    $replyCount,
                                                    $manualAgainst ? '是' : '否',
                                                    $delayAgainst ? '是' : '否',
                                                    $checkDetailModel->id,
                                                ];
                                            }
                                        }
                                    } else {

                                        $contents[] = [
                                            date('Y-m-d H:i:s', $checkDetailModel->submitTime),
                                            $shops[$shopId]['shopCode'] ?? 0,
                                            $shops[$shopId]['name'] ?? '',
                                            $regionName,
                                            $addressPrefixArr[0] ?? '',
                                            $addressPrefixArr[1] ?? '',
                                            $checkDetailModel->dealName,
                                            $checkDetailModel->companyName ?: '-',
                                            $councilorName,
                                            self::getUsername($firstAuditUid),
                                            $firstProcessReject,
                                            self::getUsername($kfAuditUid),
                                            $kfProcessReject,
                                            $project['text'],
                                            $inputObj->checkResult(),
                                            $inputObj->checkImages(),
                                            '-',
                                            '-',
                                            $inputObj->problemDesc(0)[0] ?? '',
                                            $inputObj->rectifyStatusText(),
                                            $inputObj->rectifyDesc(),
                                            $inputObj->rectifyImages(),
                                            $inputObj->lastSubmitTime($cruiseCheckRectify),
                                            $inputObj->rectifyOrderStatus($cruiseCheckRectify),
                                            $inputObj->rectifyAuditResult($cruiseCheckRectify),
                                            $replyCount,
                                            $manualAgainst ? '是' : '否',
                                            $delayAgainst ? '是' : '否',
                                            $checkDetailModel->id,
                                        ];
                                    }
                                }

                                break;
                        }
                    }
                }
            });
        }, 'cruise_check_details.id', 'dId');

        $ossDetail = ExportService::export($params['filename'], $headers, $contents);

        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }

        return $path;
    }

    public static function getRiskName12(int $riskType2): array
    {
        return Cache::store('array')->remember("getRiskName:{$riskType2}", 600, function () use ($riskType2) {
            $query = CruiseCheckRiskProblemModel::query()->where('riskType2', $riskType2)->first();
            if (!$query) {
                return ['', ''];
            }

            return [$query->riskName1, $query->riskName2];
        });
    }

    public static function getUsername(int $userId): string
    {
        return Cache::store('array')->remember("tmp_username:{$userId}", 600, function () use ($userId) {

            if (!$userId) {
                return '';
            }

            $user = KmsUser::query()->where('rmsUserId', $userId)->first();
            if ($user) {
                return $user->name . "（{$user->nickname}）";
            }

            // 调接口
            return (new RmsUserApi())->getUserInfoByIds([$userId], ['id', 'username'])['data'][0]['username'] ?? '';
        });
    }

    public function detail(int $id)
    {
        $item = CruiseCheckDetailModel::query()
                                      ->with('cruiseOrderRel')
                                      ->with('cruiseTaskRel')
                                      ->find($id);
        if (!$item) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的巡检报告");
        }

        if ($item->reportResult == CruiseCheckDetailModel::REPORT_RESULT_INIT) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "巡检报告未完成");
        }

        if (!$item->cruiseOrderRel) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "订单状态错误");
        }

        $inputs = (new CheckInputService($item->cruiseOrderRel->id, 0))->getInputObjectFill()['lists'] ?? [];

        $signatureImgs = [];
        foreach ($inputs as $input) {
            foreach ($input['projects'] as $i) {
                switch ($i["inputType"]){
                    case AttributeCruiseSupport::INPUT_TYPE_SIGNATURE:
                    case AttributeCruiseSupport::INPUT_TYPE_PAYEE_INFO:
                        $signatureImgs = $i['value'] ?? [];
                        break;
                }
            }
        }

        $shopInfo       = (new RmsShopApi())->getShopByIds([$item->cruiseOrderRel->shopId])['data']['shopList'][0] ?? [];
        $shopCode       = $shopInfo['shopCode'] ?? '';
        $merchantUserId = (int)OpenShopSignOrderModel::query()
                                                     ->where('shopCode', $shopCode)
                                                     ->orderByDesc('id')
                                                     ->value('merchantUserId');
        $merchantName   = RmsUserService::getRmsUserInfoByUserIds([$merchantUserId])['data'][0]['username'] ?? '';

        // 机构信息
        if ($item->cruiseOrderRel->cruiseCheckCompanyId) {
            $cruiseCheckCompany = CruiseCheckCompanyModel::getDataById($item->cruiseOrderRel->cruiseCheckCompanyId);
        } else {
            $cruiseCheckCompany = [];
        }

        // 审核日志
        $process = CruiseOrderProcessModel::query()
                                          ->where('cruiseOrderId', $item->orderId)
                                          ->where('step', CruiseOrderProcessModel::PROCESS_SELF_REVIEWED)
                                          ->orderByDesc('id')
                                          ->first();

        $successNum = 0;
        $failNum = 0;

        foreach ($inputs as $input) {
            foreach ($input['projects'] as $i) {
                if (in_array($i['inputType'], AttributeCruiseSupport::CRUISE_CHECK_MODULE)) {

                    if ($i['value'] == AttributeCruiseSupport::CRUISE_CHECK_OK) {
                        $successNum++;
                    } elseif ($i['value'] == AttributeCruiseSupport::CRUISE_CHECK_FAIL) {
                        $failNum++;
                    }
                }
            }
        }

        $totalNum = $successNum + $failNum;
        $successRate = $totalNum ? bcdiv($successNum * 100, $totalNum, 2) . '%' : '-';

        // 督导
        $manager = OpenShopOrderManagerModel::query()
                                            ->where('shopId', $item->cruiseOrderRel->shopId)
                                            ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                                            ->where('managerUid', '!=', 0)
                                            ->orderByDesc('id')
                                            ->first();
        $ddName = $manager->managerName ?? '';

        return [
            'shops'  => [
                'shopCode'     => $shopInfo['shopCode'] ?? '',
                'shopName'     => $shopInfo['name'] ?? '',
                'address'      => $shopInfo['address'] ?? '',
                'merchantName' => $merchantName,
            ],
            'company' => [
                'companyName'    => $cruiseCheckCompany['fsCompany']['name'] ?? '',
                'companyContact' => $cruiseCheckCompany['companyManager']['name'] ?? '',
                'companyPhone'   => $cruiseCheckCompany['companyManager']['phone'] ?? '',
                'kfManager'      => $cruiseCheckCompany['kfManager']['name'] ?? '',
            ],
            'check'  => [
                'sysTemplate'     => $item->sysTemplate,
                'sysTemplateText' => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$item->sysTemplate] ?? '',
                'dealName'        => $item->dealName,
                'templateName'    => (string)optional($item->cruiseTaskRel)->name,
                'submitTime'      => $item->submitTime ? date('Y-m-d H:i:s', $item->submitTime) : '',
                'failNum'         => $item->failNum,
                'checkNum'        => $item->totalNum,
                'totalScore'      => $item->totalScore,
                'successScore'    => $item->actualScore, // 实际得分
                'actualScore'     => $item->totalScore != 0 ? (int)($item->actualScore / $item->totalScore * 100) : 0,
                'reportResult'    => $item->reportResult,
                'signatureImgs'   => $signatureImgs,
                'qualityScore'    => $item->qualityScore,
            ],
            'audit' => [
                'status'    => $item->cruiseOrderRel->status,
                'auditTime' => $process ? $process->createdAt->toDateTimeString() : '',
                'userId'    => $uid = $process ? $process->createdByUid : 0,
                'userName'  => KmsUser::getUserInfo([$uid])[$uid] ?? '',
                'errorNum'  => $failNum,
                'successRate' => $successRate,
                'ddName'    => $ddName,
            ],

            // 合格/不合格 二合一
            'inputs' => $inputs,

            // 待整改、待审核、已整改 三合一
            'rectifyInputs' => (new CruiseCheckRectifyService(0, 0))->reportsListsGroupByRectifyStatus($id),
        ];
    }
}

